import React, { useState, useContext } from 'react';
import { Link } from 'react-router-dom';
import { FaReply, FaThumbsUp, FaTrashAlt } from 'react-icons/fa';
import { AuthContext } from '../../contexts/AuthContext';
import CommentForm from './CommentForm';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';

const CommentItem = ({ comment, onReply, onLike, onDelete, depth = 0 }) => {
  const { user } = useContext(AuthContext);
  const [showReplyForm, setShowReplyForm] = useState(false);
  
  const formattedDate = comment.createdAt 
    ? formatDistanceToNow(new Date(comment.createdAt), { addSuffix: true, locale: zhCN })
    : '';
  
  const canDelete = user && (user.id === comment.author.id || user.role === 'ADMIN');
  
  const handleReplySubmit = async (replyData) => {
    const success = await onReply(comment.id, replyData);
    if (success) {
      setShowReplyForm(false);
    }
    return success;
  };

  return (
    <div className={`comment-item ${depth > 0 ? 'ml-6 md:ml-12 border-l-2 border-gray-200 dark:border-dark-700 pl-4' : ''}`}>
      <div className="flex items-start space-x-4 mb-4">
        <Link to={`/user/${comment.author.username}`}>
          <img
            src={comment.author.avatar || '/default-avatar.png'}
            alt={comment.author.username}
            className="w-10 h-10 rounded-full object-cover"
          />
        </Link>
        
        <div className="flex-1">
          <div className="bg-gray-50 dark:bg-dark-800 rounded-lg p-4">
            <div className="flex items-center justify-between mb-2">
              <Link to={`/user/${comment.author.username}`} className="font-medium text-gray-900 dark:text-white hover:underline">
                {comment.author.username}
              </Link>
              <span className="text-xs text-gray-500 dark:text-gray-400">{formattedDate}</span>
            </div>
            
            <div className="prose dark:prose-dark max-w-none text-gray-700 dark:text-gray-300">
              {comment.content}
            </div>
          </div>
          
          <div className="flex items-center mt-2 text-sm">
            <button 
              onClick={() => setShowReplyForm(!showReplyForm)}
              className="flex items-center text-gray-500 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-500 mr-4"
            >
              <FaReply className="mr-1" /> 回复
            </button>
            
            <button 
              onClick={() => onLike(comment.id)}
              className={`flex items-center mr-4 ${
                comment.liked ? 'text-primary-600' : 'text-gray-500 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-500'
              }`}
            >
              <FaThumbsUp className="mr-1" />
              <span>{comment.likes || 0}</span>
            </button>
            
            {canDelete && (
              <button 
                onClick={() => onDelete(comment.id)}
                className="flex items-center text-gray-500 dark:text-gray-400 hover:text-red-600 dark:hover:text-red-500"
              >
                <FaTrashAlt className="mr-1" /> 删除
              </button>
            )}
          </div>
          
          {showReplyForm && (
            <div className="mt-4">
              <CommentForm onSubmit={handleReplySubmit} parentId={comment.id} />
            </div>
          )}
        </div>
      </div>
      
      {comment.replies && comment.replies.length > 0 && (
        <div className="replies">
          {comment.replies.map(reply => (
            <CommentItem
              key={reply.id}
              comment={reply}
              onReply={onReply}
              onLike={onLike}
              onDelete={onDelete}
              depth={depth + 1}
            />
          ))}
        </div>
      )}
    </div>
  );
};

const CommentList = ({ comments, onReply, onLike, onDelete, isLoading, error }) => {
  if (isLoading) {
    return (
      <div className="comment-list py-4 text-center text-gray-500 dark:text-gray-400">
        加载评论中...
      </div>
    );
  }
  
  if (error) {
    return (
      <div className="comment-list py-4 text-center text-red-500">
        加载评论失败，请稍后重试
      </div>
    );
  }
  
  if (!comments || comments.length === 0) {
    return (
      <div className="comment-list py-4 text-center text-gray-500 dark:text-gray-400">
        暂无评论，快来发表第一条评论吧！
      </div>
    );
  }
  
  // 只显示顶级评论，回复在各个评论项内显示
  const topLevelComments = comments.filter(comment => !comment.parentId);
  
  return (
    <div className="comment-list space-y-6">
      {topLevelComments.map(comment => (
        <CommentItem
          key={comment.id}
          comment={comment}
          onReply={onReply}
          onLike={onLike}
          onDelete={onDelete}
        />
      ))}
    </div>
  );
};

export default CommentList;